package api

import (
	"crypto/md5"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/e421083458/golang_common/lib"
	"github.com/gin-gonic/gin"
	"github.com/gogf/gf/util/gconv"
	"micro-server/middleware"
	"micro-server/router/routerInit"
	"micro-server/vender/baiduApi/input"
	"net/url"
	"time"
)

const (
	baiduAppId  = "20210716000889441"
	baiduAppKey = "zrADy8FnJTLf_binuk4z"
)

type baiduErr struct {
	ErrorCode string `json:"error_code"`
	ErrorMsg  string `json:"error_msg"`
}

type transResult struct {
	Src string `json:"src"`
	Dst string `json:"dst"`
}

// {"from":"en","to":"zh","trans_result":[{"src":"apple","dst":"\u82f9\u679c"}]}
type Trans struct {
	baiduErr
	From        string        `json:"from"`
	To          string        `json:"to"`
	TransResult []transResult `json:"trans_result"`
}

func BaiduTrans(query string, from string, to string) (result Trans, err error) {
	salt := gconv.String(time.Now().Unix())
	// appid+q+salt+密钥的MD5值
	sign := fmt.Sprintf("%x", md5.Sum([]byte(baiduAppId+query+salt+baiduAppKey)))
	a := url.Values{
		"q":     {query},
		"from":  {from},
		"to":    {to},
		"appid": {baiduAppId},
		"salt":  {salt},
		"sign":  {sign},
	}
	urlS := "https://api.fanyi.baidu.com/api/trans/vip/translate"
	_, b, err := lib.HttpGET(lib.NewTrace(), urlS, a, 1000, nil)
	if err != nil {
		return
	}
	err = json.Unmarshal(b, &result)
	if err != nil {
		return
	}
	return
}

type Api struct {
}

func RegisterTrans() {
	api := Api{}
	routerInit.ApiNormalGroup.Handle("POST", "trans", api.baiduTrans)
}

func (a *Api) baiduTrans(gc *gin.Context) {
	params := &input.TransInput{}
	if err := params.BindingParams(gc); err != nil {
		middleware.ErrorOut(gc, middleware.PARMAS_ERROR, err)
		return
	}
	result, err := BaiduTrans(params.Content, params.From, params.To)
	if err != nil {
		middleware.ErrorOut(gc, middleware.RUN_ERROR, err)
		return
	}
	if result.ErrorCode != "" {
		b, _ := json.Marshal(baiduErr{
			result.ErrorCode,
			result.ErrorMsg,
		})
		err = errors.New(string(b))
		middleware.ErrorOut(gc, middleware.RUN_ERROR, err)
		return
	}
	middleware.SuccessOut(gc, result.TransResult, middleware.SUCCESS)
}
